<template>
  <DynModule
    ref="jzlPageItem"
    class="ele-design-item jzl-page-item"
    :class="[{ 'active': isCurrent }]"
    :key="item?.page_item_code"
    @click.native.stop="handleClick"
    @mousemove.native.stop="handleMouseOver"
    @mouseenter.native.stop="handleMouseEnter"
    @mouseleave.native.stop="handleMouseLeave"
    :def="item"
    :is-h5="isH5"
    :is-design="true"
    :page-type="pageType"
    :current-item="currentItem"
    v-bind="$attrs">
<!--    <div slot="header" v-if="item.component === 'jzlPageSub'" class="ele-design-subpage-tag"></div>
    <template slot="box" v-if="item.component === 'jzlLayout'">
      <div v-if="!item.subs || item.subs.length <= 0" class="layout-empty-tip"></div>
      <template v-for="it in item.subs">
        <BuilderItem
          :item="it"
          :is-h5="isH5"
          :page-type="pageType"
          :items="item.subs"
          v-bind="$attrs"
          :current-item="currentItem"
          :current-el-code="currentElCode"
        />
      </template>
    </template>-->
  </DynModule>
</template>

<script setup>
import _ from 'lodash'
import {computed, watch, onMounted, onUnmounted} from "vue";
import { $themeUtils, $utils } from '@jzl/utils'

defineOptions({
  name: 'BuilderItem'
})

const emit = defineEmits(['selectItem', 'itemEnter', 'itemLeave'/*, 'eleNodeTreeChange'*/])
const props = defineProps({
  item: Object,
  isH5: Boolean,
  pageType: [Number, String],
  items: Object,
  currentItem: Object,
  // currentElCode: String,
  // key: [String, Number]
})

const isCurrent = computed(() => {
  let itemCode = _.get(props.item, 'page_item_code');
  let currentItemCode = _.get(props.currentItem, 'page_item_code');

  return itemCode && itemCode === currentItemCode;
})

const itemTip = computed(() => {
  let component = _.get(props.item, 'component');
  let w = props.item.w;
  let h = props.item.h;
  let tip = `类型: ${component}`;

  if (!_.isEmpty(w)) tip += ` 宽: ${w}`;
  if (!_.isEmpty(h)) tip += ` 高: ${h}`;

  return tip;
})

onMounted(() => {
  document.addEventListener('mousemove', clearHover)
})

onUnmounted(() => {
  document.removeEventListener('mousemove', clearHover);
})

watch(() => props.item?.subs, (newVal, oldVal) => {
  if (newVal && oldVal && newVal.length !== oldVal.length) {
    // emit("eleNodeTreeChange");
    $bus.emit('design:changeElemNodes')
  }
})

const _getTargetEleName = (target, paths) => {
  let eleName = null;
  if (target && target.getAttribute) {
    eleName = target.getAttribute("j-name") || target.getAttribute("j-name");
  }

  if (eleName) return eleName;

  if (paths && paths.length) {
    for (let i = 0; i < paths.length; i++) {
      let ele = paths[i];

      if (ele && ele.getAttribute) {
        eleName = ele.getAttribute("j-name") || ele.getAttribute("name");
      }

      if (eleName) return eleName;
    }
  }

  // 自己没有再向上查，最多5级
  let parentNode = target;
  for(let i = 0; i < 5; i++) {
    parentNode = parentNode?.parentNode;
    if(!parentNode) break;
    eleName = parentNode?.getAttribute("j-name") || parentNode?.getAttribute("name");
    if(eleName) return eleName;
  }

  return null;
}

const handleClick = (e) => {
  // console.log(e);
  let paths = _.get(e, "path");
  // 应该target 在前，但是 icon svg
  let target = _.get(e, "target") || _.get(e, 'currentTarget');
  let eleName = _getTargetEleName(target, paths);

  emit("selectItem", {
    targetEleName: eleName,
    item: props.item,
    items: props.items
  });

  $bus.emit('design:clickNode', {
    targetEleName: eleName,
    item: props.item,
    items: props.items
  })
}

const getClosestEle = (ele) => {
  if (!ele) return null;

  for (let i = 0; i < 10; i++) {
    let name = ele && ele.getAttribute ? ele.getAttribute("name") : null;
    if (!ele || name) {
      return ele;
    }

    ele = ele.parentNode;
  }

  return null;
}

const handleMouseOver = _.throttle((e) => {
  let ele = getClosestEle(e.target);

  if (ele) {
    let code = ele.getAttribute("name");
    $bus.emit('design:hoverEleCode', code);
    // let cs = window.getComputedStyle(ele);
    // console.log(ele.getAttribute("name"), `width: ${ cs.getPropertyValue('width') }, height: ${ cs.getPropertyValue('height') }`)

    /*let $exists = window.document.querySelectorAll(`.jzl-design-ele-hover`);

    _.each($exists, existEle => {
      if (existEle != ele) {
        $themeUtils.removeClass(existEle, "jzl-design-ele-hover");
      }
    });

    $themeUtils.addClass(ele, "jzl-design-ele-hover");*/
  }
}, 200)

const clearHover = () => {
  let $exists = window.document.querySelectorAll(`.jzl-design-ele-hover`);

  _.each($exists, existEle => {
    $themeUtils.removeClass(existEle, "jzl-design-ele-hover");
  });
}

const handleMouseEnter = (e) => {
  emit("itemEnter", props.item.page_item_code);
}

const handleMouseLeave = (e) => {
  emit("itemLeave", props.item.page_item_code);
  $themeUtils.removeClass(e.target, "jzl-design-ele-hover");
}
</script>
